<?php
// +----------------------------------------------------------------------
// | INPHP
// | Copyright (c) 2023 https://inphp.cc All rights reserved.
// | Licensed ( https://opensource.org/licenses/MIT )
// | Author: 幺月儿(https://gitee.com/lulanyin) Email: inphp@qq.com
// +----------------------------------------------------------------------
// | 服务入口
// +----------------------------------------------------------------------
namespace Inphp\Core;

use Inphp\Core\Services\Http\Server;
use Inphp\Core\Services\IServer;

class Service
{
    /**
     * 运行基于CLI
     * @var string
     */
    const CLI = 'cli';

    /**
     * 运行基于PHP-FPM
     * @var string
     */
    const FPM = 'fpm';

    /**
     * CLI服务端类型：http
     */
    const HTTP = 'http';

    /**
     * CLI服务端类型：websocket
     * 如果使用了该类型，也会开启http服务
     */
    const WEBSOCKET = 'websocket';

    /**
     * 服务对象
     * @var Server
     */
    public static Server $server;

    /**
     * 初始化
     * @param bool $cli
     * @param string $type
     * @return IServer
     */
    public static function init(bool $cli = false, string $type = 'http'): IServer
    {
        //保存服务运行方式
        !defined('INPHP_SERVICE_PROVIDER') && define("INPHP_SERVICE_PROVIDER", $cli ? self::CLI : self::FPM);
        //实例化服务对象
        $type = $type == 'ws' ? self::WEBSOCKET : $type;
        $type = in_array($type, [self::HTTP, self::WEBSOCKET]) ? $type : 'http';
        return self::$server = new Server($cli, $type);
    }

    /**
     * 运行各模块提供的CMD对象
     * @return IServer
     */
    public static function cmd(): IServer
    {
        return new \Inphp\Core\Services\Cmd\Server();
    }

    /**
     * 是否运行于CLI
     * @return bool
     */
    public static function isCLI(): bool
    {
        return defined('INPHP_SERVICE_PROVIDER') && INPHP_SERVICE_PROVIDER === self::CLI;
    }
}